package crmdna.payment;

import static crmdna.common.OfyService.ofyCrmDna;
import crmdna.client.Client;
import crmdna.common.APIException;
import crmdna.common.APIResponse.Status;
import crmdna.common.Utils;

public class Token {

	static void save(TokenProp tokenProp) {
		Client.ensureValid(tokenProp.client);
		ensureValidToken(tokenProp.token);

		Utils.ensureNotNullOrEmpty(tokenProp.paypalLogin,
				"Paypal login is null or empty");
		Utils.ensureNotNullOrEmpty(tokenProp.paypalPwd,
				"Paypal password is null or empty");
		Utils.ensureNotNullOrEmpty(tokenProp.paypalSecret,
				"Paypal secret is null or empty");
		Utils.ensureNonZero(tokenProp.registrationId, "registrationId is zero");

		TokenEntity tokenEntity = new TokenEntity();
		tokenEntity.token = tokenProp.token;
		tokenEntity.registrationId = tokenProp.registrationId;
		tokenEntity.client = tokenProp.client;
		tokenEntity.paypalLogin = tokenProp.paypalLogin;
		tokenEntity.paypalPwd = tokenProp.paypalPwd;
		tokenEntity.paypalSecret = tokenProp.paypalSecret;
		tokenEntity.sandbox = tokenProp.sandbox;

		ofyCrmDna().save().entity(tokenEntity).now();
	}

	static TokenProp safeGet(String token) {

		ensureValidToken(token);
		TokenEntity tokenEntity = ofyCrmDna().load().type(TokenEntity.class)
				.id(token).get();

		if (token == null)
			throw new APIException(Status.ERROR_RESOURCE_NOT_FOUND,
					"Cannot find paypal token [" + token
							+ "] in CRMDNA datastore");

		return tokenEntity.toProp();
	}

	static void ensureValidToken(String token) {
		if ((token == null) || token.equals("")) {
			Utils.throwIncorrectSpecException("Invalid token [" + token + "]");
		}
	}
}
